package com.mine.androidlearn.api.sign;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;


/**
 *  签名工具
 *
 * @author mine
 * @version V1.0 2018/8/6 22:34
 */
public class SignTool {

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }

    /**
     * @param map 无序的参数map
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @Description: 生成签名字符串
     * @author wangxiaojie
     */
    public static String createSign(Map<String, String> map)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        Map<String, String> m = sortMapByKey(map);
        if (m == null) {
            return null;
        }
        // 根据参数map构造有序的字符串 如key=1value=v1key=2value=v2....
        for (String key : m.keySet()) {
            // 图片头像不签名 支付宝同步返回json不签名
            if (!"avatar".equals(key) && !"payResult".equals(key)) {
                sb.append("key=").append(key).append("value=").append(map.get(key));
            }
        }
        // 加入盐值 随机数 构造新的字符串
        sb.append(map.get("sr"));
        // 进行md5加密
        String md5Str1 = Md5Util.getStringMD5(sb.toString(), "UTF-8").toLowerCase();
        // 加密后的密文串加入盐值时间戳 构造新的字符串,进行md5加密
        String md5Str2 = Md5Util.getStringMD5(md5Str1 + map.get("ts"), "UTF-8").toLowerCase();
        return md5Str2;
    }

    /**
     * 获取1000~9999之间的随机数
     *
     * @return
     * @author zhangjiajie
     */
    public static int getSecurityRandom() {
        int max = 9999;
        int min = 1000;
        SecureRandom random = new SecureRandom();
        return random.nextInt(max) % (max - min + 1) + min;
    }

    /**
     * 比较器类
     *
     * @author wangxiaojie
     * @version: V1.0  2017/4/13
     */
    private static class MapKeyComparator implements Comparator<String>, Serializable {
        public int compare(String str1, String str2) {
            return str1.compareTo(str2);
        }
    }
}
